import uuid
from util.CaptchaUtil import get_code,create_captcha
from entry.Entrys import Captcha,CaptchaBack
from util.Timer import *
from flask import json
from util.JwtUtil import cerateToken
from util.Service import *
from util.PwdUtil import createHashPwd
""" 验证码信息缓存 """
__cache = dict()

#  此系统目前没有使用redis 所以验证码 暂时放于代码中缓存

""" 清除所有验证码 """
def clearAllCaptcha():
    print('清理验证码')
    __cache.clear()
    print(__cache.items().__len__())
""" 清除验证码 """
def clearCaptcha(token):
    __cache.pop(token)
    
def clearExceed():
    # print("清除验证码中")
    for key in __cache.keys():
        key:str
        item:CaptchaBack = __cache.get(key)
        if(datetime.utcnow().timestamp()>item.initTime+500):
            clearCaptcha(token= key)
    # print("清除完成")

t= True
""" 获取验证码 """
def getCaptcha():
    global t
    if t :
        t = False
        setInterval(clearAllCaptcha,300000)
    code = get_code(6)
    img = create_captcha(code, 150, 60, 25, noise_points=320)
    token = str(uuid.uuid4())
    # print(f"\"code\":\"{code}\",\n\"token\":\"{token}\"")
    initTimt = datetime.utcnow().timestamp()
    # print(initTimt)
    r = CaptchaBack(time=initTimt,code=code)
    __cache.setdefault(token,r)
    return Captcha(img = img,token = token).__dict__


""" 验证验证码 """
def authCaptcha(token,code:str,time=5,login = False) -> bool|None:
    # time 单位为分钟
    captcha_cfg:dict = Config.getConfigByKey('##Captcha')
    if login and captcha_cfg and captcha_cfg.get('value') =='off':
        return True
    try:
        # 将time 转换为分钟
        time = time*60
        codeinfo:CaptchaBack = __cache.get(token)
        if(codeinfo == None):
            return None
        now = datetime.utcnow().timestamp()
        if((codeinfo.initTime + time) > now):
            # print(codeinfo.initTime + time,now)
            if(code.lower() == codeinfo.code.lower()):
                return True
        else:
            return None
        clearCaptcha(token=token)
        return False
    except:
        return False

""" 登陆 """
def signIn(uname,pwd:str):
    info = User.hasUserByUP(uname,createHashPwd(uname,pwd))
    if(info == None):
        return 0
    elif info['status'] == '0':
        return 1
    pld = {
        'id':info['uId'],
        'username':info['username'],
        'initTime':info['initTime'],
        'loginTime': datetime.utcnow()
    }
    return cerateToken(pld)

""" 注册 """
def signUp(form:dict):
    u = form.get('username')
    if(User.getUserByUsername(u)):
        return 0
    form['password'] = createHashPwd(u,form.get('password'))
    form['initTime'] = datetime.utcnow()
    form['status'] = '1'
    form['head'] = 'User'
    User.addUser(form)
    return 1

def hasUser(username):
    return User.hasUserByUsername(username)

def roleSignIn(uid:int,rid:int):
    if(not User.hasUserRole(uid,rid)):
        return False
    user = User.getUserById(uid)
    if(user.get('status') != '1'):
        return False
    if Role.getRoleStatus(rid)!= '1':
        return False
    return cerateToken({
        'id':uid,
        'rid':int(rid),
        'username':user.get('username'),
        'nickname':user.get('nickname'),
        'exceed':datetime.utcnow()
    })
        

    